<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>用户管理</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="../../layuimini/lib/layui-v2.5.5/css/layui.css" media="all" />
  <link rel="stylesheet" href="../../layuimini/css/public.css" media="all" />
  <style>
    .hidden {
      display: none;
    }
  </style>
</head>

<body>
  <div class="layuimini-container">
    <div class="layuimini-main">
      <fieldset class="table-search-fieldset">
        <legend>搜索信息</legend>
        <div style="margin: 10px 10px 10px 10px">
          <form class="layui-form layui-form-pane" action="">
            <div class="layui-form-item">
              <label class="layui-form-label">账号:</label>
              <div class="layui-input-inline">
                <input id="user_name_id" name="name" placeholder="请输入账号" class="layui-input" />
              </div>

              <div class="layui-inline">
                <button type="submit" class="layui-btn" lay-submit lay-filter="data-search-btn">
                  <i class="layui-icon layui-icon-search"></i> 搜 索
                </button>

                <button type="button" class="layui-btn layui-btn-primary" id="data-reset-btn">
                  <i class="layui-icon"></i> 重 置
                </button>
              </div>
            </div>
          </form>
        </div>
      </fieldset>

      <script type="text/html" id="toolbarDemo">
          <div class="layui-btn-group">
            <button class="layui-btn layui-btn layui-btn-sm" lay-event="add">
              添加
            </button>
            <button
              class="layui-btn layui-btn-sm layui-btn-danger"
              lay-event="delete"
            >
              删除
            </button>
            <button
              class="layui-btn layui-btn-sm layui-btn-warm"
              lay-event="refresh"
            >
              刷新
            </button>
          </div>
        </script>

      <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
    </div>
  </div>

  <script type="text/html" id="userEditDialog">
      <form
        id="userEditForm"
        lay-filter="userEditForm"
        class="layui-form layuimini-form"
        style="padding-left:20px;margin-top: 20px;padding-right: 50px;"
      >
        <div class="layui-form-item">
          <label class="layui-form-label required">账号:</label>

          <div class="layui-input-block">
            <input
              type="text"
              name="username"
              placeholder="账号"
              class="layui-input"
              lay-verType="tips"
              lay-verify="required"
              autocomplete="off"
            />
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label required">密码:</label>
          <div class="layui-input-block">
            <input
              type="password"
              name="password"
              data="passworedtype"
              placeholder="密码"
              class="layui-input"
              autocomplete="off"
              id="password1"
              lay-verify="required"
              lay-verType="tips"
            />
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label required">确认密码:</label>
          <div class="layui-input-block">
            <input
              type="password"
              name="password2"
              placeholder="确认密码"
              class="layui-input"
              autocomplete="off"
              id="password2"
              lay-verify="required"
              lay-verType="tips"
            />
          </div>
        </div>

        <div class="layui-form-item">
          <label class="layui-form-label"></label>
          <button
            class="layui-btn layui-btn-normal"
            lay-filter="userEditSubmit"
            lay-submit
          >
            提交
          </button>
          <button class="layui-btn layui-btn-primary" type="button" id="Cancel">
            取消
          </button>
        </div>
      </form>
    </script>

  <script type="text/html" id="currentTableBar">
      <a class="layui-btn layui-btn-xs" lay-event="user_role">分配角色</a>
      <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="reset_pwd"
        >重置密码</a
      >
      <!-- <a class="layui-btn layui-btn-normal layui-btn-sm" lay-event="edit"
        >编辑</a
      > -->
      <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete"
        >删除</a
      >
    </script>

  <!-- 分配角色 -->
  <script type="text/html" id="userAddRoleDialog">
      <form
        id="userAddRoleForm"
        lay-filter="userAddRoleForm"
        class="layui-form"
        style="padding-left:20px;margin-top: 20px; padding-right: 20px;"
      >
        <!-- 穿梭框 -->
        <div id="userAddRoleTransfer"></div>
        <div
          class="layui-form-item hidden"
        >
          <button
            id="submit_btn"
            class="layui-btn layui-btn-normal"
            lay-filter="userAddRoleSubmit"
            lay-submit
          >
            提交
          </button>
          <button
            class="layui-btn layui-btn-primary"
            type="button"
            ew-event="closeDialog"
            id="Cancel"
          >
            取消
          </button>
        </div>
      </form>
    </script>

  <script src="../../layuimini/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
  <script src="../../layuimini/js/lay-config.js" charset="utf-8"></script>

  <script>
    layui.use(
      ["layer", "form", "table", "common", "transfer", "util"],
      function () {
        var $ = layui.jquery,
          form = layui.form,
          table = layui.table,
          common = layui.common,
          transfer = layui.transfer,
          util = layui.util;

        var tableIns = table.render({
          elem: "#currentTableId",
          url: common.api + "/user/list",
          where: { token: common.getToken },
          toolbar: "#toolbarDemo",
          title: "账号信息",
          cols: [
            [
              {
                type: "checkbox",
                width: 50,
              },
              {
                field: "userId",
                width: 100,
                title: "用户ID",
                align: "center",
                sort: true,
              },
              {
                field: "username",
                maxWidth: 300,
                title: "账号",
                align: "center",
              },
              {
                field: "roleDesc",
                title: "角色",
                minWidth: 300,
                align: "center",
              },
              {
                title: "操作",
                width: 240,
                toolbar: "#currentTableBar",
                align: "center",
              },
            ],
          ],
          limits: [1, 5, 10, 15, 20],
          limit: 10,
          page: true,
          skin: "row",
          even: true,
          parseData: function (res) {
            if (res.code != 200) {
              common.login(res);
            }
            return {
              code: res.code, //解析接口状态
              msg: res.msg, //解析提示文本
              count: res.data.total, //解析数据长度
              data: res.data.list, //解析数据列表
            };
          },
          response: {
            statusCode: 200, //重新规定成功的状态码为 200，table 组件默认为 0
          },
          request: {
            pageName: "page", //页码的参数名称，默认：page
            limitName: "size", //每页数据量的参数名，默认：limit
          },
          initSort: {
            field: "userId",
            type: "asc",
          },
        });

        //监听工具栏添加删除刷新
        table.on("toolbar(currentTableFilter)", function (obj) {
          if (obj.event === "add") {
            // 监听添加操作
            showEditModel();
          } else if (obj.event === "delete") {
            // 监听删除操作
            var data = table.checkStatus("currentTableId").data;
            if (data.length === 0) {
              layer.msg("请选择要删除的数据", { icon: 2 });
              return;
            }
            var ids = data.map(function (d) {
              return d.userId;
            });
            doDel(ids);
          } else if (obj.event === "refresh") {
            tableIns.reload({
              url: common.api + "/user/list",
              method: "get",
              // where: {},
            });
          }
        });

        function getData() {
          var data = [];
          $.ajax({
            url: common.api + "/role/list", //后台数据请求地址
            type: "get",
            headers: { authorization: common.getToken("token") },
            async: false,
            success: function (resut) {
              data = resut.data;
            },
          });
          return data;
        }
        // 获取用户角色列表
        function getUserRoles(userId) {
          var data = [];
          $.ajax({
            url: common.api + "/user/" + userId + "/getUserRoles", //后台数据请求地址
            type: "get",
            async: false,
            headers: { authorization: common.getToken("token") },
            success: function (resut) {
              data = resut.map((item) => item.roleId);
            },
          });
          return data;
        }

        // 用户分配角色
        function showUserRoleDialog(val) {
          var idx = layer.open({
            type: 1,
            area: ["720px", "500px"],
            title: "分配角色",
            // offset:'100px',
            anim: 1,
            shade: 0.6,
            content: $("#userAddRoleDialog").html(),
            btn: ["提交", "取消"],
            btn2: function (index, layero, that) {
              // 取消
              // return true;
            },
            btn1: function (index, layero, that) {
              // 提交
              $("#submit_btn").click();
            },
            success: function (layero, dIndex) {
              // 穿梭框
              transfer.render({
                elem: "#userAddRoleTransfer",
                title: ["未分配角色", "已分配角色"], //自定义标题
                data: getData(),
                value: getUserRoles(val),
                showSearch: true,
                parseData: function (res) {
                  return {
                    value: res.roleId, // 数据值
                    title: res.roleName + "(" + res.roleDescription + ")", // 数据标题
                    // "disabled": res.name==='admin'?true:false,  // 是否禁用
                    // "checked": res.checked // 是否选中
                  };
                },
                id: "user_role_id",
                width: 290, // 定义宽度
                height: 360, // 定义高度
              });

              // 表单提交事件
              form.on("submit(userAddRoleSubmit)", function () {
                var selectRoles = transfer.getData("user_role_id");
                console.log(1111, selectRoles);
                var roleIds = selectRoles.map((element) => element.value);
                var userRole = {};
                userRole.userId = val;
                userRole.roleIds = roleIds;
                common.ajax(
                  common.api + "/user/saveRoles",
                  JSON.stringify(userRole),
                  function (res) {
                    if (res.code === 200) {
                      layer.close(dIndex);
                      layer.msg(res.msg, { icon: 1 });
                      setTimeout(() => {
                        table.reload("currentTableId");
                      }, 1000);
                    } else {
                      layer.msg(res.msg, { icon: 2 });
                    }
                  },
                  "post",
                  function (data) {
                    layer.msg(data.msg, { icon: 2 });
                  },
                  false,
                  true
                );
                return false;
              });

              $("#Cancel").click(function () {
                layer.close(idx);
              });
            },
          });
        }

        //监听编辑删除
        table.on("tool(currentTableFilter)", function (obj) {
          if (obj.event === "edit") {
            showEditModel(obj.data);
          } else if (obj.event === "delete") {
            doDel([obj.data.userId]);
          } else if (obj.event === "user_role") {
            showUserRoleDialog(obj.data.userId);
          } else if (obj.event === "reset_pwd") {
            // 重置密码
            resetPwd(obj.data);
          }
        });
        // 重置密码
        function resetPwd(data) {
          layer.confirm(
            "确定要重置用户【" + data.username + "】的登录密码吗？",
            {
              skin: "layui-layer-admin",
              shade: 0.1,
            },
            function (i) {
              // 确认

              layer.prompt(
                { title: "请输入密码", formType: 1 },
                function (value, index, elem) {
                  if (value === "") return elem.focus();
                  // 关闭 prompt
                  var newpassword = util.escape(value);
                  if (newpassword.length < 4) {
                    layer.msg("密码长度不能少于4位", { icon: 2 });
                    return;
                  }

                  var userform = {};
                  userform.password = newpassword;
                  userform.username = data.username;
                  userform.id = data.id;
                  common.ajax(
                    common.api + "/user/" + data.userId,
                    JSON.stringify(userform),
                    function (res) {
                      if (res.code === 200) {
                        layer.msg(res.msg, { icon: 1 });
                        layer.close(index);
                        table.reload("currentTableId");
                      } else {
                        layer.msg(res.msg, { icon: 2 });
                      }
                    },
                    "put",
                    function (data) {
                      layer.msg(data.msg, { icon: 2 });
                    }
                  );
                  return false;

                  layer.close(index);
                }
              );
              // 取消
              layer.close(i);
            }
          );
        }

        //显示添加弹窗
        function showEditModel(formData) {
          var idx = layer.open({
            type: 1,
            area: ["500px", "300px"],
            title: formData ? "编辑" : "添加",
            anim: 1,
            shade: 0.6,
            content: $("#userEditDialog").html(),
            success: function (layero, dIndex) {
              // 回显表单数据
              form.val("userEditForm", formData);

              // 表单提交事件
              form.on("submit(userEditSubmit)", function (data) {
                if (
                  data.field.password.length < 4 ||
                  data.field.password2.length < 4
                ) {
                  layer.msg("密码长度不能少于4位", { icon: 2 });
                  return false;
                }

                if (data.field.password !== data.field.password2) {
                  layer.msg("密码输入不一致", { icon: 2 });
                  $("#password1").val("");
                  $("#password2").val("");
                  return false;
                }
                common.ajax(
                  formData
                    ? common.api + "/user/" + formData.id
                    : common.api + "/user/register",
                  JSON.stringify(data.field),
                  function (res) {
                    if (res.code === 200) {
                      layer.close(dIndex);
                      layer.msg(res.msg, { icon: 1 });
                      // 1000毫秒之后刷新table
                      setTimeout(() => {
                        table.reload("currentTableId");
                      }, 1000);
                    } else {
                      layer.msg(res.msg, { icon: 2 });
                    }
                  },
                  formData ? "put" : "post",
                  function (data) {
                    layer.msg(data.msg, { icon: 2 });
                  },
                  false,
                  true
                );
                return false;
              });

              $("#Cancel").click(function () {
                layer.close(idx);
              });
            },
          });
        }

        function doDel(ids) {
          layer.confirm(
            "确定要删除选中数据吗？",
            {
              skin: "layui-layer-admin",
              shade: 0.1,
            },
            function (i) {
              common.ajax(
                common.api + "/user/delete",
                JSON.stringify(ids),
                function (res) {
                  if (res.code === 200) {
                    layer.msg(res.msg, { icon: 1 });
                    tableIns.reload();
                  } else {
                    layer.msg(res.msg, { icon: 2 });
                  }
                },
                "DELETE",
                function (data) {
                  console.log(data);
                  layer.msg(data.msg, { icon: 2, time: 1000 });
                  return;
                }
              );
              layer.close(i);
            }
          );
        }

        layer.ready(function () { });
        // 监听搜索操作
        form.on("submit(data-search-btn)", function (data) {
          var param = data.field;
          // return false
          // 执行搜索重载
          tableIns.reload({
            url: common.api + "/user/list",
            method: "get",
            where: param,
          });
          return false;
        });
        // 监听重置操作
        $("#data-reset-btn").click(function () {
          $("#user_name_id").val("");
          tableIns.reload({
            url: common.api + "/user/list",
            method: "get",
            where: { name: "" },
          });
        });
      }
    );
  </script>
</body>

</html>